import re

from django_redis import get_redis_connection
from rest_framework import serializers
from rest_framework_jwt.settings import api_settings

from users.models import User


class CreateUserSerializer(serializers.ModelSerializer):
    password2 = serializers.CharField(min_length=8, max_length=20, write_only=True)
    sms_code = serializers.CharField(min_length=6, max_length=6, write_only=True)
    allow = serializers.CharField(write_only=True)
    token = serializers.CharField(read_only=True)

    class Meta:
        model = User
        fields = ('id','username','password','password2','mobile','sms_code','allow','token')
        extra_kwargs = {
            'username':{
                'min_length': 5,
                'max_length': 20,
                'error_messages': {
                    'min_length': '要求用户名最小为5个字符',
                    'max_length': '要求用户名最大为20个字符',
                }
            },

            'password': {
                'write_only': True,
                'min_length': 8,
                'max_length': 20,
                'error_messages': {
                    'min_length': '要求用户名最小为8个字符',
                    'max_length': '要求用户名最大为20个字符',
                }
            }
        }

    def validate_username(self, value):
        if User.objects.filter(username=value).count():
            raise serializers.ValidationError('用户名已经被注册')
        return value

    def validate_mobile(self, value):
        if User.objects.filter(mobile=value).count():
            raise serializers.ValidationError('手机号已经被注册')
        if not re.match(r'1[3-8]\d{9}$', value):
            raise serializers.ValidationError('手机号格式错误')
        return value

    def validate_allow(self, value):
        if value != 'true':
            raise serializers.ValidationError('用户协议未勾选')
        return value

    def validate(self, attrs):
        password = attrs['password']
        password2 = attrs['password2']
        mobile = attrs['mobile']
        sms_code = attrs['sms_code']
        if password != password2:
            raise serializers.ValidationError('两次密码输入不一致')
        redis_con = get_redis_connection('verify')
        real_sms_code = redis_con.get('sms_code_%s' % mobile)
        if not real_sms_code:
            raise serializers.ValidationError('手机号错误')
        if real_sms_code.decode() != sms_code:
            raise serializers.ValidationError('短信验证码错误')
        return attrs

    def create(self, validated_data):
        user = User.objects.create_user(
            username=validated_data['username'],
            password=validated_data['password'],
            mobile=validated_data['mobile']
        )
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        user.token = token
        return user









